<template>
  <div>
    <el-button type="primary" @click="form.dialogFormVisible = true"> <el-icon>
        <Plus />
      </el-icon>新增</el-button>
    <el-button type="primary" @click="deletedRangeGood()"><el-icon>
        <Delete />
      </el-icon>删除</el-button>
    <el-button type="primary" @click="form.dialogFormVisible2 = true"><el-icon>
        <FolderRemove />
      </el-icon>导入</el-button>

    <el-button type="primary" @click="DownGoodList()"><el-icon>
        <FolderOpened />
      </el-icon>导出溯源码</el-button>
  </div>
  <div>
    <el-table :data="goodList" style="width: 100%;text-align: center;" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="goodId" label="序号" />
      <el-table-column prop="goodName" label="商品名称" />
      <el-table-column prop="goodBatch" label="生产批次" />
      <el-table-column prop="goodShelf" label="保质期（天）" />
      <el-table-column prop="goodNoSc" label="生产许可证号" />
      <el-table-column prop="goodFirm" label="生产企业" />
      <el-table-column prop="goodPerfect" label="信息完善度">
        <template #default="scope">
          <span v-if="scope.row.goodPerfect / 8 == 1" style="color: green;">{{ scope.row.goodPerfect / 8 * 100
            }}%</span>
          <span v-else style="color: red;">{{ (scope.row.goodPerfect / 8 * 100).toFixed(2) }}%</span>

        </template>
      </el-table-column>
      <el-table-column prop="goodCreatePeople" label="创建人" />
      <el-table-column prop="goodCreateTime" label="创建时间" />
      <el-table-column prop="goodUpdatePeople" label="修改人" />
      <el-table-column label="操作" width="250px">
        <template #default="scope">
          <el-button type="text" style="color: #337ecc;" @click="goodDetail(scope.row)">详情</el-button>
          <el-button type="text" @click="goodFind(scope.row)">修改</el-button>
          <el-button type="text">导出溯源码</el-button>
          <el-button type="text" @click="deletedGood(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 添加 -->
  <div>
    <el-dialog v-model="form.dialogFormVisible" title="基本信息" width="500">
      <el-form :model="goodForm" label-width="auto">
        <el-form-item label="商品名称：" :label-width="140">
          <el-input v-model="goodForm.goodName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生产批次：" :label-width="140">
          <el-input v-model="goodForm.goodBatch" autocomplete="off" />
        </el-form-item>
        <el-form-item label="保质期（天）：" :label-width="140">
          <el-input v-model="goodForm.goodShelf" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生产许可证号：" :label-width="140">
          <el-input v-model="goodForm.goodNoSc" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生产企业：" :label-width="140">
          <el-input v-model="goodForm.goodFirm" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面图：" :label-width="140">
          <el-upload v-model:file-list="fileList" action="https://localhost:7169/api/Good/LoadImages"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :on-success="successImages" :limit="1" :on-exceed="handleexceed">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="goodForm.goodImage" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="emptyData()">取消</el-button>
          <el-button type="primary" @click="addGood()">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 修改 -->
  <div>
    <el-dialog v-model="form.dialogFormVisible1" title="修改基本信息" width="500">
      <el-form :model="goodForm" label-width="auto">
        <el-form-item label="商品名称：" :label-width="140">
          <el-input v-model="goodForm.goodName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生产批次：" :label-width="140">
          <el-input v-model="goodForm.goodBatch" autocomplete="off" />
        </el-form-item>
        <el-form-item label="保质期（天）：" :label-width="140">
          <el-input v-model="goodForm.goodShelf" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生产许可证号：" :label-width="140">
          <el-input v-model="goodForm.goodNoSc" autocomplete="off" />
        </el-form-item>
        <el-form-item label="生产企业：" :label-width="140">
          <el-input v-model="goodForm.goodFirm" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面图：" :label-width="140">
          <el-upload v-model:file-list="fileList" action="https://localhost:7169/api/Good/LoadImages"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :on-success="successImages" :limit="1" :on-exceed="handleexceed">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="goodForm.goodImage" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="emptyData()">取消</el-button>
          <el-button type="primary" @click="updateGood()">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 导入 -->
  <div>
    <el-dialog v-model="form.dialogFormVisible2" title="导入文件" width="500">
      <span style="cursor: pointer;" @click="loadFile">点击下载导入模板</span>
      <el-upload class="upload-demo" drag action="https://localhost:7169/api/Good/LoadAddGood"
        multiple :on-success="successFile" :on-error="errorFile">

        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          在这里放置文件或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            小于5MB的xlsx文件
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
  <div>
    <el-pagination v-model:current-page="form.pageindex" v-model:page-size="form.pagesize" :page-sizes="[3, 5, 8, 10]"
      :background="true" layout="total, sizes, prev, pager, next, jumper" prev-text="上一页" next-text="下一页"
      :total="form.listcount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useCounterStore } from '@/stores/counter'
const store = useCounterStore();
const router = useRouter();
const route = useRoute();
const form = reactive({
  pageindex: 1,
  pagesize: 10,
  listcount: 0,
  pagecount: 0,
  dialogFormVisible: false,
  dialogFormVisible1: false,
  dialogFormVisible2: false,
  goodArray: [],
})
const goodList = ref([])
const getGoodList = () => {
  axios.get('https://localhost:7169/api/Good/GetGoods', { params: form })
    .then((res) => {
      console.log(res.data)
      goodList.value = res.data.list
      form.listcount = res.data.listcount
      form.pagecount = res.data.pagecount

    })
}
const goodForm = reactive({
  goodId: '',
  goodName: '',
  goodBatch: '',
  goodShelf: '',
  goodNoSc: '',
  goodFirm: '',
  goodPerfect: 0,
  goodImage: '',
  goodCreatePeople: '',
  goodCreateTime: '',
  goodUpdatePeople: '',

})
//添加
const addGood = () => {
  goodForm.goodCreatePeople = store.UserNickname
  goodForm.goodCreateTime = new Date().toLocaleString()
  console.log(goodForm)
  axios.post('https://localhost:7169/api/Good/AddGoods', goodForm)
    .then(res => {
      console.log(res)
      if (res.data > 0) {
        ElMessage.success('添加成功')
        emptyData()
        getGoodList()
      }
      else {
        ElMessage.error('添加失败')
      }
    })
    .catch(err => {
      console.log(err)
    })
}
//清空
const emptyData = () => {
  form.dialogFormVisible = false
  form.dialogFormVisible1 = false
  goodForm.goodId = ''
  goodForm.goodName = ''
  goodForm.goodBatch = ''
  goodForm.goodShelf = ''
  goodForm.goodNoSc = ''
  goodForm.goodFirm = ''
  goodForm.goodPerfect = 0
  goodForm.goodImage = ''
  goodForm.goodCreatePeople = ''
  goodForm.goodCreateTime = ''
  goodForm.goodUpdatePeople = ''
  fileList.value = []
  // console.log()

}
//分页
const handleSizeChange = (val: number) => {
  form.pagesize = val
  getGoodList()
}
const handleCurrentChange = (val: number) => {
  form.pageindex = val
  getGoodList()
}
//全选反选
const handleSelectionChange = (val: any) => {
  form.goodArray = val
  console.log(form.goodArray)
}
//批量删除
const deletedRangeGood = () => {
  if (form.goodArray.length == 0) {
    ElMessage.error('请先选择要删除的商品')
    return;
  }
  ElMessageBox.confirm(
    `确认删除已选的 ${form.goodArray.length} 个溯源商品？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.post('https://localhost:7169/api/Good/DeletedGood', form.goodArray)
        .then(res => {
          console.log(res)
          if (res.data > 0) {
            ElMessage.success(`已删除 ${res.data} 个溯源商品`)
            getGoodList()
          }
          else {
            ElMessage.error('删除失败，请稍后再试')

          }
        })
        .catch(err => {
          console.log(err)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })

}

//单删
const deletedGood = (row: any) => {
  form.goodArray.length = 0;
  form.goodArray.push(row)
  // console.log(form.goodArray)
  ElMessageBox.confirm(
    `确认删除已选的 ${form.goodArray.length} 个溯源商品？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.post('https://localhost:7169/api/Good/DeletedGood', form.goodArray)
        .then(res => {
          console.log(res)
          if (res.data > 0) {
            ElMessage.success(`已删除 ${res.data} 个溯源商品`)
            getGoodList()
          }
          else {
            ElMessage.error('删除失败，请稍后再试')

          }
        })
        .catch(err => {
          console.log(err)
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}
//反填
const goodFind = (row: any) => {
  goodForm.goodId = row.goodId
  goodForm.goodName = row.goodName
  goodForm.goodBatch = row.goodBatch
  goodForm.goodShelf = row.goodShelf
  goodForm.goodNoSc = row.goodNoSc
  goodForm.goodFirm = row.goodFirm
  goodForm.goodPerfect = row.goodPerfect
  goodForm.goodImage = row.goodImage
  goodForm.goodCreatePeople = row.goodCreatePeople
  goodForm.goodCreateTime = row.goodCreateTime
  goodForm.goodUpdatePeople = row.goodUpdatePeople
  fileList.value = [{ url: row.goodImage, name: row.goodImage }]
  form.dialogFormVisible1 = true

}
//修改
const updateGood = () => {
  goodForm.goodUpdatePeople = store.UserNickname
  axios.post('https://localhost:7169/api/Good/UpdateGood', goodForm)
    .then(res => {
      console.log(res)
      if (res.data > 0) {
        ElMessage.success('修改成功')
        emptyData()
        getGoodList()
      }
      else {
        ElMessage.error('修改失败')
      }
    })
    .catch(err => {
      console.log(err)
    })
}
//导出
const DownGoodList = () => {
  location.href = 'https://localhost:7169/api/Good/DownLoadExcel'
}
// 下载导入模板
const loadFile=()=>{
  location.href = 'https://localhost:7169/商品溯源导出数据.xlsx'
}
//导入成功
const successFile=()=>{
  ElMessage.success('导入成功')
  form.dialogFormVisible2 = false
  getGoodList()
}
//导入失败
const errorFile=()=>{
  ElMessage.success('导入成功')
}
//详情
const goodDetail = (row: any) => {
  store.GoodId=row.goodId
  let goodStr=JSON.stringify(row)
  // console.log(goodStr)
  localStorage.setItem("goodDetail",goodStr)
  router.push({ name: 'GoodDetailView' })
}
onMounted(() => {
  getGoodList()
})
//上传
import type { UploadProps, UploadUserFile } from 'element-plus'

const fileList = ref<UploadUserFile[]>([

])

const dialogVisible = ref(false)
//上传成功
const successImages = ((response: any) => {

  console.log(response)

  goodForm.goodImage = 'https://localhost:7169/' + response
}
)
//删除图片
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
//预览图片
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  goodForm.goodImage = uploadFile.url!
  dialogVisible.value = true
}
//超出限制
const handleexceed = () => {
  ElMessage.error('只能上传一张图片')
}
</script>